package com.yc.cloud.basic.config;

import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.hutool.core.util.StrUtil;

/**
 * @Author Kent Jiang
 * @Date 2020/6/4 16:59
 * @Version 1.0
 */
@Component
public class PathUtils {



    @Autowired
    private PathConfig pathConfig;

    private static PathConfig config;

    @PostConstruct
    void init() {
        config = pathConfig;
    }

    /**
     * 基础路径
     *
     * @return 返回基础路径
     */
    public static String getBasePath() {
        return config.getBasePath();
    }

    public static String getTempBasePath() {
        return config.getTempBasePath();
    }

    /**
     * 基础URL
     *
     * @return 返回基础URL路径
     */
    public static String getBaseUrl() {
        return config.getBaseUrl();
    }


    public static String convertNetUrl(String path) {
        if (StrUtil.isNotEmpty(path)) {
            // 先获取基础URL和相对路径
            String baseUrl = PathUtils.getBaseUrl();
            String relativePath = path.replace(PathUtils.getBasePath(), "").replace(File.separator, "/");
            
            // 只对相对路径进行编码
            try {
                String encodedPath = URLEncoder.encode(relativePath, StandardCharsets.UTF_8.name())
                    .replace("+", "%20")  // 空格编码为 %20
                    .replace("%2F", "/"); // 保持斜杠不变
                return baseUrl + encodedPath;
            } catch (Exception e) {
                return baseUrl + relativePath;
            }
        }
        return "";
    }

    /**
     * URL编码路径中的中文字符
     * @param url 原始URL
     * @return 编码后的URL
     */
    private static String encodeUrl(String url) {
        if (url == null || url.isEmpty()) {
            return url;
        }
        
        try {
            String[] parts = url.split("/");
            StringBuilder result = new StringBuilder();
            
            for (int i = 0; i < parts.length; i++) {
                if (i > 0) {
                    result.append("/");
                }
                result.append(URLEncoder.encode(parts[i], StandardCharsets.UTF_8.name())
                    .replace("+", "%20"));
            }
            
            return result.toString();
        } catch (Exception e) {
            return url;
        }
    }


}
